//
//  GZAlarmManageController.swift
//  GZMarathon
//
//  Created by apple on 2021/10/27.
//

import UIKit
import MJRefresh
import SVProgressHUD

class GZAlarmManageController: EBBaseViewController{

    @IBOutlet weak var searchBar: SSSearchBar!
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var healthBtn: UIButton!
    
    @IBOutlet weak var antiBtn: UIButton!
    
    @IBOutlet weak var rateLabel: UILabel!
    
    @IBOutlet weak var cameraBtn: UIButton!
    
    var dataSource: [GZAlarmList] = []
    
    var curPage: Int = 0
    
    var alarmType: Int = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        confUI()
        searchBar.delegate = self
        navigationController?.navigationBar.isHidden = true
    }
    
    func confUI() {
        confSearchBar()
        confTableView()
    }
    
    func confSearchBar() {
        let maskPath = UIBezierPath(roundedRect: cameraBtn.bounds, byRoundingCorners: [.topLeft, .bottomLeft], cornerRadii: CGSize(width: 20, height: 20))
        let maskLayer = CAShapeLayer();
        maskLayer.frame = view.bounds;
        maskLayer.path = maskPath.cgPath;
        cameraBtn.layer.mask = maskLayer;
        searchBar.tintColor = .lightGray
    }
    
    func confTableView() {
        tableView.register(UINib(nibName: "GZAlarmListCell", bundle: nil), forCellReuseIdentifier: "alarm_list")
        tableView.rowHeight = 52
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.curPage = 0
            self?.getAlarmList()
        })
//        tableView.mj_footer = MJRefreshAutoFooter(refreshingBlock: {[weak self] in
//            self?.curPage += 1
//            self?.getAlarmList()
//        })
        tableView.mj_header?.beginRefreshing()
    }
    
    func endRefresh(){
        tableView.mj_header?.endRefreshing()
        tableView.mj_footer?.endRefreshing()
    }

    func getAlarmList(){
        //0:防疫告警  1:健康告警
        ApiProvider.request(EBAPI.getAlarmList(alarmName: searchBar.text, alarmType: "\(alarmType)", alarmStatus: nil), model: GZAlarmData.self) {[weak self] data, isSuccess in
            self?.endRefresh()
            guard let dt = data else{
                return
            }
            
            if self?.curPage == 0{
                self?.dataSource.removeAll()
            }
            self?.dataSource.append(contentsOf: dt.data)
            self?.tableView.reloadData()
        }
        
    }

    
    @IBAction func clickHeatlthBtn(_ sender: UIButton) {
        
        if healthBtn.isSelected {
            return
        }
        rateLabel.text = "心率 "
        healthBtn.isSelected = true
        antiBtn.isSelected = false
        healthBtn.backgroundColor = .white
        antiBtn.backgroundColor = UIColorFromRGB(0xF4F7FF)
        
        
        self.alarmType = 1
        tableView.mj_header?.beginRefreshing()
    }
    
    @IBAction func clickAntiBtn(_ sender: UIButton) {
        
        if antiBtn.isSelected {
            return
        }
        rateLabel.text = "防疫码"
        antiBtn.isSelected = true
        healthBtn.isSelected = false
        antiBtn.backgroundColor = .white
        healthBtn.backgroundColor = UIColorFromRGB(0xF4F7FF)
        
        self.alarmType = 0
        tableView.mj_header?.beginRefreshing()
    }
    
    @IBAction func clickCameraBtn(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            self.present(cameraPicker, animated: true, completion: nil)
        } else {
            print("不支持拍照")
        }
                
    }
    
    @IBAction func clickEmergencyBtn(_ sender: UIButton) {
        let phone = "telprompt://" + "120"
        if UIApplication.shared.canOpenURL(URL(string: phone)!) {
            UIApplication.shared.openURL(URL(string: phone)!)
        }
    }
    
    
    func recognitFace(img: UIImage) {
        
        
        guard let imageData = img.compressImageMid(maxLength: 1024*1024)else{
            SVProgressHUD.showError(withStatus: "图片压缩失败")
            return
        }
        
        
        let data = img.jpegData(compressionQuality: 0.03)
        let imgxxx = UIImage(data: data!)!
        
        
        SVProgressHUD.show()
        ApiLoadingProvider.request(EBAPI.recognitFace(base64Str: imgxxx.base64Str()), model: GZPersonInfo.self) {[weak self] model, isSuccess in
            SVProgressHUD.dismiss()
            guard let md = model else{
                return
            }
            if md.code != 200{
                SVProgressHUD.showError(withStatus: md.message)
                return
            }
            
            let vc = GZPersonInfoController(info: md)
            self?.navigationController?.pushViewController(vc, animated: true)
        }
                
    }
    
}
extension GZAlarmManageController: UINavigationControllerDelegate, UIImagePickerControllerDelegate{
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        self.dismiss(animated: true, completion: nil)
        let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
        recognitFace(img: image)
        self.dismiss(animated: true, completion: nil)
    }
 
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
    
}


extension GZAlarmManageController: UITableViewDelegate, UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "alarm_list", for: indexPath) as! GZAlarmListCell
        let alarm = dataSource[indexPath.row]
        cell.nameLabel.text = alarm.parti_name
        cell.numberLabel.text = alarm.alarm_uid
        cell.rateLabel.text = "123"
//        cell.nameLabel.text = alarm.parti_name
//        cell.numberLabel.text = alarm.parti_phone
        if alarmType == 1 {
            //健康告警
            cell.codeImgView.isHidden = true
            cell.rateLabel.isHidden = false
            cell.rateLabel.text = alarm.alarm_content
        }else{
            //防疫告警
            cell.codeImgView.isHidden = false
            cell.rateLabel.isHidden = true
            cell.rateLabel.text = ""
        }
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let vc = GZPersonInfoController(alarmList: dataSource[indexPath.row])
        navigationController?.pushViewController(vc, animated: true)
    }
    
    
}



extension GZAlarmManageController: UISearchBarDelegate{
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.getAlarmList()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.getAlarmList()
    }
    
    
}
